import java.util.*;


class Anagram {
    
	public static void main(String args[]){
		System.out.println("Enter two strings to check if they are anagrams: ");
		Scanner in = new Scanner(System.in);
		String initialPhrase = in.nextLine();
        String anagramPhrase = in.nextLine();
        in.close();
        
        if (initialPhrase.equals(anagramPhrase)) {          //prevent user from cheating
			System.out.println("The initial and anagram strings are equal. You must re-arrange letters to get a valid anagram!");
			return;
		}
        
		initialPhrase = initialPhrase.toLowerCase().replaceAll("\\s","");   // addapt input strings removing all spaces and setting all to lower case
		anagramPhrase = anagramPhrase.toLowerCase().replaceAll("\\s","");
		
        if (isAnagram(initialPhrase, anagramPhrase)) {
            System.out.println("The entered strings are anagrams");
        } else {
            System.out.println("The entered strings are NOT anagrams"); 
        }
	}
    
    private static boolean isAnagram(String initialPhrase, String anagramPhrase) {
        String oneSymbolFromInitial;
        String oneSymbolFromAnagram;
        boolean isAnagram = false;
        OutermostLoop:
        for (int i = 0; i < initialPhrase.length(); i++) {                //compare each symbol from initialPhrase to each symbol from anagramPhrase
            oneSymbolFromInitial = initialPhrase.substring(i, i + 1);     // pick up one(ith) symbol from initial string
            for (int j = 0; j < anagramPhrase.length(); j++) {
                oneSymbolFromAnagram = anagramPhrase.substring(j, j + 1); //pick up one(jth) symbol from anagram string
                if (oneSymbolFromInitial.equals(oneSymbolFromAnagram)) {
                    isAnagram = true;
                    anagramPhrase = anagramPhrase.replaceFirst(oneSymbolFromAnagram, ""); //delete a symbol from anagram once it was found
                    break;
                }
                else {
                    isAnagram = false;
                }
            }
            if (!isAnagram) break OutermostLoop;
        }
        return isAnagram;
    }  
}